const fs = require("fs");
const puppeteer = require("puppeteer");
var URL = "http://bet.hkjc.com/marksix/Fixtures.aspx?lang=CH";
(async () => {
  const browser = await puppeteer.launch({
    headless: false
  });
  const page = await browser.newPage();
  // 进入页面
  await page.goto(URL);

  // 等待頁面重新加载之后
  await page.waitForNavigation({
    waitUntil: "load"
  });
  const dataJson = await page.evaluate(() => {
    return window.dataJson;
  });

  var drawYear = dataJson.drawDates.drawYear;


  // drawYear.map(async (item, index) => {
  //   var nian = item["@year"]; //年份
  //   var yue = item["drawMonth"][0]["@month"]; // 第一个月份
  //   // 
  //   let qishu = nian + 001;
  //   if(yue != "1"){
  //     qishu = await getQSJson([nian, yue], page)
  //   }
  //   getQiQhuBody(nian, item.drawMonth, qishu);
  // });

  var promises = drawYear.map(async (item, index) => {
    var nian = item["@year"]; //年份
    var yue = item["drawMonth"][0]["@month"]; // 第一个月份
    // 
    let qishu = nian + "001";
    if(yue != "1"){
      qishu = await getQSJson([nian, yue], page)
    }
    let drawMonth = item.drawMonth
    return {nian,drawMonth,qishu}
  });
 
  Promise.all(promises).then((datas)=>{
    var fs = require('fs')
    fs.writeFile("./data/" + "autohk6" + ".txt", '', function(){
      datas.forEach((data)=>{
        let {nian,drawMonth,qishu} = data
        getQiQhuBody(nian, drawMonth, qishu);
      })
    })
    browser.close();
  })
 
})();

async function getQSJson(arr, page) {
    let year = arr[0] + "";
    let month = doubleNum(arr[1]);
    var sd = year + month + "01";
    var ed = year + month + new Date(year, month, 0).getDate();
    var url =`https://bet.hkjc.com/marksix/getJSON.aspx?sd=${sd}&ed=${ed}&sb=0`;
    let response  = await page.goto(url)
    let result  = await response.json()
    let current = result[result.length-1];
    return year + current.id.split("/")[1]
}

function getQiQhuBody(year, monthArr, firstqishu) {
  var body = []; // 要写进的主体
  var qishu;
  monthArr.map((e, i) => {
    var month = e["@month"];
    var dayArr = e["drawDate"];
    dayArr.map((item, index) => {
      if (item["@draw"] == "1" || item["@jackpot"] == "1") {
        qishu = firstqishu++;
        body.push({
          itemCode: "HK6",
          qishu: qishu,
          data: year + "-" + doubleNum(month) + "-" + doubleNum(item['@date'])
        });
      }
    });
  });
  savedContent(body);
}

function savedContent(new_art) {
  var body = "";
  new_art.map(function(item, i) {
    body += `${item.itemCode},${item.qishu},${item.qishu},${
      item.data
    } 21:30:00,${item.data} 09:30:00\r\n`;
  });
  // var body = JSON.stringify(new_art);
  fs.appendFile("./data/" + "autohk6" + ".txt", body, "utf-8", function(err) {
    if (err) {
      console.log(err);
    }
  });
}

function doubleNum(str) {
  if (str < 10) {
    return "0" + str;
  } else {
    return str;
  }
}
